import React, {Component} from 'react';
import {Button, Card, Table, Modal, Tag, Radio, Form, Input, InputNumber, message, Upload} from "antd";
import './style.less'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { getUsers, addUser, editUser, deleteUser} from "../../api/user";
import axios from 'axios'

class Index extends Component {
    constructor(props){
        super(props);
        this.addFormRef = React.createRef();
        this.editFormRef = React.createRef();
        this.formEditRef = React.createRef();
        this.state = {
            total: 0,
            pageSize: 6,
            current: 1,
            pageSizeOptions: [6,8,10,12,14],
            loading: false,
            tableLoading: false,
            confirmLoading: false,
            imageUrl: '',
            filelist: [],
            dataSource: [],
            addIsVisible: false,
            editIsVisible: false,
            columns: [
                {
                  title: '账号',
                  dataIndex: 'number',
                  key: 'number'
                },
                {
                    title: '姓名',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '头像',
                    dataIndex: 'avater',
                    key: 'avater',
                    render: (avater) => {
                        return avater?<img src={avater} style={{width: '50px',height: '40px'}} alt="头像加载中..."/>: <span>未设置头像</span>
                    }
                },
                {
                    title: '年龄',
                    dataIndex: 'age',
                    key: 'age',
                    render: (age) => {
                        let color = 'green';
                        if (age > 30){
                            color= 'red'
                        }
                        return <Tag color={color}>{age}</Tag>
                    }
                },
                {
                    title: '电话',
                    dataIndex: 'iphone',
                    key: 'iphone'
                },
                {
                    title: '身份证',
                    dataIndex: 'identity',
                    key: 'identity'
                },
                {
                    title: '邮箱',
                    dataIndex: 'email',
                    key: 'email'
                },
                {
                  title: '可用状态',
                  dataIndex: 'isUsed',
                  key: 'isUsed',
                  render: (isUsed) => {
                      const color = isUsed ? 'red': 'green';
                      const text = isUsed ? '否': '是';
                      return <Tag color={color}>{text}</Tag>
                  }
                },
                {
                    title: '操作',
                    key: 'action',
                    render: (text,record,index) => {
                        return <Radio.Group size='default'>
                            <Button value='mod' onClick={this.editUser.bind(this,record)} type='primary'>编辑</Button>
                            <Button value='delete' onClick={this.deleteUser.bind(this,{text,record,index})} type='error'>{record.isUsed ? '解封' : '冻结'}</Button>
                        </Radio.Group>;
                    }
                }
            ],
            layout: {
                labelCol: {
                    span: 6,
                },
                wrapperCol: { span: 12 },
            },
            tailLayout: {
                wrapperCol: { span: 6, offset: 6},
            }
        }
    }

    //添加用户
    addUser = () => {
        this.setState({
            addIsVisible: true
        })
    }

    //页码改变的回调
    paginationChange = (current,pageSize) => {
        this.setState({
            current,
            pageSize: pageSize
        })
    }

    //每页条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({
            current: 1,
            pageSize: size
        })
    }

    //取消添加用户
    addCancel =() => {
        this.setState({
            addIsVisible: false,
            imageUrl: ''
        })
    }

    //确认添加用户
    addOk = () => {
        this.setState({
            confirmLoading: true
        })
        const data = this.addFormRef.current.getFieldsValue();

        addUser(data).then(res => {
            this.init();
            message.success(res.msg);
            this.addFormRef.current.setFieldsValue({
                number: '',
                passWord: '',
                name: '',
                age: '',
                iphone: '',
                avater: '',
                identity: '',
                email: ''
            })
            this.setState({
                imageUrl: ''
            })
        }).catch(err => {
            message.error('用户注册失败')
            this.setState({
                confirmLoading: false
            })
        }).finally(() => {
            this.setState({
                confirmLoading: false
            })
        })
    }

    //编辑用户信息
    editUser = (record) => {
        const {number,name,avater,age,iphone,identity,email} = record;
        this.setState({
            editIsVisible: true,
            imageUrl: avater
        },() => {
            setTimeout(() => {
                this.editFormRef.current.setFieldsValue({
                    name,
                    number,
                    avater,
                    age,
                    iphone,
                    identity,
                    email
                })
            })
        })
    }

    //删除用户信息
    deleteUser = ({text,record,index}) => {
        deleteUser({isUsed: record.isUsed,number: record.number}).then(res => {
            message.success(res.msg);
            this.init();
        }).catch(err => {
            message.error('数据请求出错')
        })
    }

    //上传头像
    uploadAvater = ({file}) => {
        const data = new FormData();
        data.append("Token","7d366bf734da5f49ba55a59bb242d5c273bf0911:Wqdd0F4QLwgsQmdrt-cnAKLD2g8=:eyJkZWFkbGluZSI6MTU4Njk1NTIxOCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzE1NjU1IiwiYWlkIjoiMTY3ODc2NSIsImZyb20iOiJmaWxlIn0=");
        data.append('file',file);
        this.setState({
            loading: true
        })
        axios.post("http://up.imgapi.com/",data).then(res => {
            this.setState({
                imageUrl: res.data.linkurl
            })
            this.addFormRef.current.setFieldsValue({
                avater: res.data.linkurl
            })
        }).finally(() => {
            this.setState({
                loading: false
            })
        })
    }

    //上传前检验
    beforeUpload = (file) => {
        const limt = file.size/1024/1024 > 10;
        if (limt){
            message.error('文件大小超过10m,请重新选择');
            this.onRemove(file)
            return false;
        }
    }

    //删除不符合的文件
    onRemove = (fileList) => {
        this.setState({
            filelist: this.state.filelist.filter(item => {
                return item.name !== fileList.name
            })
        },() => {
            this.addFormRef.current.setFieldsValue({
                avater: '',
            })
        })
    }

    onChange = (file) => {
        this.setState({
            filelist: file.filelist
        })
    }

    //取消编辑
    editCancel = () => {
        this.setState({
            imageUrl: '',
            editIsVisible: false
        })
    }

    //修改用户信息上传头像
    uploadEditAvater = ({file}) => {
        const data = new FormData();
        data.append("Token","7d366bf734da5f49ba55a59bb242d5c273bf0911:Wqdd0F4QLwgsQmdrt-cnAKLD2g8=:eyJkZWFkbGluZSI6MTU4Njk1NTIxOCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzE1NjU1IiwiYWlkIjoiMTY3ODc2NSIsImZyb20iOiJmaWxlIn0=");
        data.append('file',file);
        this.setState({
            loading: true
        })
        axios.post("http://up.imgapi.com/",data).then(res => {
            this.setState({
                imageUrl: res.data.linkurl
            })
            this.editFormRef.current.setFieldsValue({
                avater: res.data.linkurl
            })
        }).finally(() => {
            this.setState({
                loading: false
            })
        })
    }

    //确认修改
    editOk = () => {
        this.setState({
            confirmLoading: true
        })
        const data = this.editFormRef.current.getFieldsValue();
        editUser(data).then(res => {
            message.success(res.msg);
            this.init();
        }).catch(err => {
            message.error('修改失败')
        }).finally(() => {
            this.setState({
                confirmLoading: false
            })
        })
    }


    //初始化数据
    init = () => {
        getUsers().then(res => {
            const dataSource = res.data.map(item => {
                return {
                    key: item.id,
                    number: item.number,
                    name: item.name,
                    avater: item.avater,
                    age: item.age,
                    iphone: item.iphone,
                    identity: item.identity,
                    email: item.email,
                    isUsed: item.isUsed
                }
            })
            this.setState({
                dataSource,
                total: res.data.length
            })
        })
    }

    componentDidMount() {
        this.init();
    }

    render() {
        const uploadButton = (
            <div>
                {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div className="ant-upload-text">上传头像</div>
            </div>
        );
        return (
            <Card title="用户管理" className='mod_card' extra={<span><Button onClick={this.addUser} type='primary' style={{marginRight: 10}}>添加用户</Button></span>}>
                <Table
                    dataSource={this.state.dataSource}
                    columns={this.state.columns}
                    pagination={{
                        total: this.state.total,
                        pageSize: this.state.pageSize,
                        showSizeChanger: true,
                        pageSizeOptions: this.state.pageSizeOptions,
                        showQuickJumper: true,
                        current: this.state.current,
                        onChange: this.paginationChange,
                        onShowSizeChange: this.onShowSizeChange
                    }}
                    loading={this.state.tableLoading}
                />
                <Modal
                    visible={this.state.addIsVisible}
                    title="添加用户"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定添加"
                    cancelText="取消"
                    onCancel={this.addCancel}
                    onOk={this.addOk}
                >
                    <Form
                        {...this.state.layout}
                        name="add_user"
                        className="add_user"
                        ref={this.addFormRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label='账号'
                            name= 'number'
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label= '密码'
                            name= 'passWord'
                        >
                            <Input.Password placeholder='请输入密码'></Input.Password>
                        </Form.Item>
                        <Form.Item
                            label="名字"
                            name="name"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label= "头像"
                            name= 'avater'
                        >
                            <Upload
                                listType="picture-card"
                                showUploadList={false}
                                beforeUpload={this.beforeUpload}
                                onRemove={this.onRemove}
                                onChange={this.onChange}
                                fileList={this.state.filelist}
                                customRequest={this.uploadAvater}
                            >
                                {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label="电话"
                            name="iphone"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="身份证"
                            name="identity"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="邮箱"
                            name="email"
                        >
                            <Input/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
                    visible={this.state.editIsVisible}
                    title="修改用户"
                    confirmLoading={this.state.confirmLoading}
                    maskClosable={false}
                    okText="确定"
                    cancelText="取消"
                    onCancel={this.editCancel}
                    onOk={this.editOk}
                >
                    <Form
                        {...this.state.layout}
                        name="add_user"
                        className="add_user"
                        ref={this.editFormRef}
                        initialValues={{ remember: true }}
                    >
                        <Form.Item
                            label='账号'
                            name= 'number'
                        >
                            <Input disabled={true}/>
                        </Form.Item>
                        <Form.Item
                            label="名字"
                            name="name"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label= "头像"
                            name= 'avater'
                        >
                            <Upload
                                listType="picture-card"
                                showUploadList={false}
                                beforeUpload={this.beforeUpload}
                                onRemove={this.onRemove}
                                onChange={this.onChange}
                                fileList={this.state.filelist}
                                customRequest={this.uploadEditAvater}
                            >
                                {this.state.imageUrl ? <img src={this.state.imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label="电话"
                            name="iphone"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="身份证"
                            name="identity"
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="邮箱"
                            name="email"
                        >
                            <Input/>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        );
    }
}

export default Index;